import Vue from 'vue';
import Vuex from 'vuex';
import clone from '@/lib/clone';
import createId from '@/lib/idCreator';
import router from '@/router';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    recordList: [] as RecordItem[],
    tagList: [] as Tag[],
    currentTag:undefined,
    selectedTags:[] as Tag[],
  } as RootState,
  mutations: {
    fetchRecords(state) {
      state.recordList = JSON.parse(window.localStorage.getItem('recordList') || '[]') as RecordItem[];
    },
    createRecord(state, record:RecordItem) {
      const record2 = clone(record);
      record2.createAt = new Date().toISOString();
      state.recordList.push(record2);
      store.commit('saveRecords');
      window.alert("已保存")
    },
    saveRecords(state) {
      localStorage.setItem('recordList', JSON.stringify(state.recordList));
    },
    fetchTags(state) {

       state.tagList = JSON.parse(window.localStorage.getItem('tagList') || '[]') || [] as RecordItem[];
       if(!state.tagList||state.tagList.length===0){
         store.commit('createTag','吃')
         store.commit('createTag','喝')
         store.commit('createTag','玩')
         store.commit('createTag','乐')
       }
    },
    createTag(state, name: string) {
      const names = state.tagList.map(item => item.name);
      if (names.indexOf(name) >= 0) {
        window.alert('标签名重复了');
        return 'duplicated';
      }
      const id = createId().toString();
      state.tagList.push({id, name: name});
      store.commit('saveTags');
      return 'success';
    },
    saveTags(state) {
      window.localStorage.setItem('tagList', JSON.stringify(state.tagList));
    },
    updateTag(state, payload: { id: string, name: string }) {
      const {id, name} = payload;
      const idList = state.tagList.map(item => item.id);
      if (idList.indexOf(id) < 0) return window.alert('not found');
      const nameList = state.tagList.map(item => item.name);
      if (nameList.indexOf(name) >= 0) return window.alert('标签名重复');
      const tag = state.tagList.filter(item => item.id === id)[0];
      tag.name = name;
      tag.id = name;
      store.commit('saveTags');
    },
    removeTag(state, id: string) {
      const index = state.tagList.findIndex(item => item.id === id);
      if (index === -1) return window.alert('删除失败');
      window.alert('删除成功');
      state.tagList.splice(index, 1);
      store.commit('saveTags');
      router.back();
    }
  }
});

store.commit('fetchRecords');
store.commit('fetchTags');

export default store;
